package com.yiphonenum.phonenumberapplication;

import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.provider.ContactsContract;
import android.widget.Toast;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;
import java.util.Random;

public class PhoneMake {

    Context _context;
    private ArrayList<String> phones_result;
    private String group_prefix;  // 组名前缀
    private int idx_current;  // 通讯录导入当前位置

    boolean cancel_write_contacts = false;
    boolean make_in_progress = false;

    public PhoneMake(Context context) {
        _context = context;
        phones_result = new ArrayList<>();
    }

    // 1、从数据表取得前缀
    private ArrayList<String> getPhonePrefix(String city, String corp) {

        ArrayList<String> phone_lead = new ArrayList<>();

        File dbFile = _context.getDatabasePath("city.db");
        String s = dbFile.toString();
        SQLiteDatabase db = SQLiteDatabase.openDatabase(s, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
        // String sql = String.format("select * from Phone where city=%s and corp=%s", city, corp);
        Cursor cursor = db.rawQuery("select * from Phone where city=? and corp=?", new String[]{city, corp});

        int i = 0;
        for (cursor.moveToFirst(); !cursor.isLast(); cursor.moveToNext()) {
            int phone_idx = cursor.getColumnIndex("phone");
            phone_lead.add(i++, cursor.getString(phone_idx));
        }
        // 关闭数据连接
        db.close();

        return phone_lead;
    }

    // 2、号码段，分别生成
    private void makeEach(HashMap<String, String> h) {
        String prefix = h.get("prefix");
        int num = Integer.parseInt(h.get("num"));

        Random random = new Random();

        HashSet<Integer> phone_nums = new HashSet<>();

        for (int i = 0; i < num; i++) {
            int r = random.nextInt();
            while (phone_nums.contains(r)) {
                r = random.nextInt();
            }
            phone_nums.add(r);
        }

        // 写到结果变量中
        Iterator<Integer> iterator = phone_nums.iterator();
        while (iterator.hasNext()) {
            phones_result.add(prefix + Integer.toString(iterator.next()));
        }
    }

    // 3、生成电话号码
    public void makePhone(String city, String corp, int limit) {
        // 清空
        phones_result.clear();
        // 分组前缀
        group_prefix = city;
        // 取号码前缀
        ArrayList<String> phones = getPhonePrefix(city, corp);
        Random random = new Random();

        // 准备结果号码
        int r;
        if (limit < phones.size()) {
            for (int i = 0; i < phones.size(); i++) {
                // 前缀数量作为外循环
                if (i >= limit) break;
                r = random.nextInt(9999);
                phones_result.add(phones.get(i) + Integer.toString(r));
            }
        } else {
            // 号码数量作为外循环
            int size = phones.size();
            for (int i = 0; i < limit; i++) {
                r = random.nextInt(9999);
                phones_result.add(phones.get(i % size) + Integer.toString(r));
            }
        }
        try {
            Toast.makeText(_context, String.format(Locale.CHINESE, "已生成号码:%d",
                    phones_result.size()), Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(_context, "生成号码失败", Toast.LENGTH_SHORT).show();
        }
        // 写号码到手机
        //addToContact();
    }


    // 4、导入通讯录
    public void addToContact() {
        if (phones_result.size() == 0) return;
        make_in_progress = true;
        // 分组名称
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA);
        String t = sdf.format(new Date());
        String group_title = group_prefix + t;

        // 创建一个分组
        ContentResolver cr = _context.getContentResolver();
        ContentValues groupValues = new ContentValues();
        groupValues.put(ContactsContract.Groups.TITLE, group_title);
        cr.insert(ContactsContract.Groups.CONTENT_URI, groupValues);

        // 添加联系人
        ArrayList<ContentProviderOperation> ops = new ArrayList<>();
        String DisplayName;
        String MobileNumber;

        idx_current = 0;

        for (int i = 0; i < phones_result.size(); i++) {
            if (cancel_write_contacts) break;  // 退出写入联系人

            DisplayName = group_prefix + "_" + String.format(Locale.CHINESE, "%04d", i);
            MobileNumber = phones_result.get(i);

            ops.clear();

            ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
                    .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, "account_name")
                    .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, "account_type").build());

            // 姓名
            ops.add(ContentProviderOperation.newInsert(
                    ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                    .withValue(ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                    .withValue(
                            ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
                            DisplayName).build());
            // 电话
            ops.add(ContentProviderOperation.newInsert(
                    ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                    .withValue(ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                    .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, MobileNumber)
                    .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
                            ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
                    .build());
            // 分组

            // 写入
            try {
                _context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(_context, "例外: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }

            idx_current ++;
        }

    }

      // 5-停止写入
    public void stop_write_contact() {
        cancel_write_contacts = true;
    }

    // 6-忙
    public boolean is_busy() {
        return make_in_progress;
    }

    // 7-结果集
    public ArrayList<String> getResult() {
        return phones_result;
    }

    // 8-清空结果集
    public  void clearResult() {
        phones_result.clear();
    }
//
}